最近博主的小伙伴们想搞个垃圾查询的小程序,奈何没有数据来源和查询API接口,博主想到 django 的 restframework 可以方便地生成API接口,于是动手搞了起来!老规矩,还是在之前 mysite 工程中继续修改,工程目录:GitHub MySite
一、新建app
为了方便管理,我这里新建一个名字为apis的app:
django-admin startapp apis
添加到全局settings中的 installed app 中:
INSTALLED_APPS = [
....
# for apis
'apis',
]
在apis app中添加urls.py文件,并在全局urls中添加一条路由:
# apis.urls 文件
from django.conf.urls import include
from django.urls import path
app_name = '[apis]'
urlpatterns = [
]
# 全局urls.py 文件 添加 如下路由
path('api/', include('apis.urls', namespace = 'apis')),
二、新建model
我们在 apis.model 中添加“垃圾”和“垃圾分类”两个model,相关属性以及代码如下:
# apis.model 文件
from django.db import models
# Create your models here.
class Category(models.Model):
name = models.CharField('分类名称', unique=True, max_length=20, help_text='分类名称,最多20个字符。')
summary = models.CharField('分类介绍', max_length=255, help_text='垃圾分类介绍。最多255字符')
class Meta:
verbose_name = '垃圾分类'
verbose_name_plural = verbose_name
ordering = ['name']
def __str__(self):
return self.name
class Rubbish(models.Model):
name = models.CharField('垃圾名称', unique=True, max_length=20, help_text='垃圾名称,最多20个字符。')
category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='分类', help_text='选择垃圾的分类')
class Meta:
verbose_name = '垃圾'
verbose_name_plural = verbose_name
ordering = ['name']
def __str__(self):
return self.name
修改apis.admin 文件,便于后台我们能方便看到数据,并且对数据进行修改。
import xadmin
from xadmin import views
from .models import Rubbish, Category
class RubbishAdmin(object):
# 菜单图标
model_icon = 'fa fa-trash'
# 分类筛选
list_filter = ('category',)
# 搜索框
search_fields = ('name',) # 指定要搜索的字段
class CategoryAdmin(object):
# 菜单图标
model_icon = 'fa fa-trash'
pass
xadmin.site.register(Rubbish, RubbishAdmin)
xadmin.site.register(Category, CategoryAdmin)
同步数据库后,我们就能在后台看到这两个字段了!
python manage.py makemigrations
python manage.py migrate
我们先随便添加点数据,添加一个有害垃圾分类,再添加一个电池垃圾,便于之后的测试。
三、集成 Rest Framework
具体可以参考 官网文档,我这里简单写一下基础的配置集成
1、安装
pip install djangorestframework
2、全局settings添加installed app,并指定相关默认权限配置等:
INSTALLED_APPS = [
...
'rest_framework',
]
# rest framework配置
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
3、添加全局路由,用于api认证:
path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
4、apis app中新建 serializers.py 文件,并添加序列化处理函数:
# apis.serializers 文件
from .models import Rubbish, Category
from rest_framework import serializers
class RubbishSerializer(serializers.ModelSerializer):
category = serializers.StringRelatedField(many=False)
class Meta:
model = Rubbish
fields = ('name', 'category')
class RubbishCategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = ('name', 'summary')
5、修改views文件,添加处理函数
# apis.views 文件
from .models import Rubbish, Category
from rest_framework import permissions, status
from rest_framework.response import Response
from .serializers import RubbishSerializer, RubbishCategorySerializer
from rest_framework.generics import RetrieveAPIView, ListAPIView
# Create your views here.
# 所有分类获取处理 继承listAPIView
class RubbishCategoryView(ListAPIView):
queryset = Category.objects.all()
serializer_class = RubbishCategorySerializer
# 单个分类获取处理 继承RetrieveAPIView 表示只可以get
class RubbishCategoryDetailView(RetrieveAPIView):
queryset = Category.objects.all()
serializer_class = RubbishCategorySerializer
def get(self, request, pk):
try:
category = Category.objects.get(name=pk)
serializer = RubbishCategorySerializer(category)
return Response(serializer.data)
except Category.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
# 所有垃圾获取处理 继承listAPIView
class RubbishView(ListAPIView):
queryset = Rubbish.objects.all()
serializer_class = RubbishSerializer
# 单个垃圾获取处理 继承RetrieveAPIView 表示只可以get
class RubbishDetailView(RetrieveAPIView):
queryset = Rubbish.objects.all()
serializer_class = RubbishSerializer
def get(self, request, pk):
try:
rubbish = Rubbish.objects.get(name=pk)
serializer = RubbishSerializer(rubbish)
return Response(serializer.data)
except Rubbish.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
6、修改apis.urls文件,添加相关路由:
from django.urls import path
from .views import RubbishView, RubbishDetailView, RubbishCategoryView, RubbishCategoryDetailView
app_name = '[apis]'
urlpatterns = [
path('laji/', RubbishView.as_view()),
path('laji/<str:pk>/', RubbishDetailView.as_view()),
path('lajifenlei/', RubbishCategoryView.as_view()),
path('lajifenlei/<str:pk>/', RubbishCategoryDetailView.as_view()),
]
四、测试api
上述所有步骤搞定之后,不出意外的话,我们的api就能成了,我们可以访问以下链接测试,如果有错,那就回头检查下吧。
1、获取所有垃圾: http://127.0.0.1:8000/api/laji/
2、获取单个垃圾 http://127.0.0.1:8000/api/laji/电池
3、获取所有分类 http://127.0.0.1:8000/api/lajifenlei/
4、获取单个分类 http://127.0.0.1:8000/api/lajifenlei/有害垃圾
就是这么简单,打完收工!找个时间再讲下 API的权限与调用问题。
《django 建站历程系列文章》